package com.liuqianfei.markme.rules.block;

import com.liuqianfei.markme.common.Utils;
import com.liuqianfei.markme.core.Token;
import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.IAction;

/**
 * Horizontal rule
 * @author liuqianfei
 */
public class HrAction implements IAction
{
    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        char marker, ch;
        Token token;
        int cnt, pos = state.getbMarks(startLine) + state.gettShift(startLine), max = state.geteMarks(startLine);

        marker = state.getSrc().charAt(pos++);

        // Check hr marker
        if (marker != 0x2A/* * */
                && marker != 0x2D/* - */
                && marker != 0x5F/* _ */)
            return false;

        // markers can be mixed with spaces, but there should be at least 3 of them

        cnt = 1;
        while (pos < max)
        {
            ch = state.getSrc().charAt(pos++);
            if (ch != marker && !Utils.isSpace(ch))
                return false;
            if (ch == marker)
                cnt++;
        }

        if (cnt < 3)
            return false;

        if (silent)
            return true;

        state.setLine(startLine + 1);

        token        = state.push("hr", "hr", 0);
        token.map    = new int[]{startLine, state.getLine()};
        token.markup = String.join(String.valueOf(marker), new String[cnt + 1]).replace("null", "");

        return true;
    }
}
